<template>
  <a-layout class="dashboard-page">
    <a-layout-sider class="dashboard-menu-sider" width="240">
      <div class="logo-info">
        <div class="logo-box">
<!--          <i class="iconfont icon-xiche"></i>-->
        </div>
        <span class="title">自助洗车</span>
      </div>
      <div class="menu-list">
        <template v-for="menu in DefMenuList" :key="menu.menuCode">
          <router-link :to="menu.path" class="menu-item" :class="currentRoutePath === menu.path ? 'active' : ''" v-if="localRoleMenuCacheObj[menu.menuCode]">
            <div class="mask-active"></div>
            <i class="iconfont" :class="menu.icon"></i>
            <span class="menu-title">{{ menu.title }}</span>
          </router-link>
        </template>
        <template v-if="hasFinanceMenus">
          <a class="menu-item sub-menu-item" @click="handleSubmenuShowChange2">
            <i class="iconfont icon-yewutubiao_caiwuguanlixitong"></i>
            <span class="menu-title">财务管理</span>
            <div class="arrow-icon">
              <i class="iconfont icon-xia" v-if="subMenuShow2"></i>
              <i class="iconfont icon-shang" v-else></i>
            </div>
          </a>
          <div class="submenu-box" v-show="subMenuShow2">
            <template v-for="menu in DefFinanceMenuList" :key="menu.menuCode">
              <router-link :to="menu.path" class="menu-item" :class="currentRoutePath === menu.path ? 'active' : ''" v-if="localRoleMenuCacheObj[menu.menuCode]">
                <div class="mask-active"></div>
                <i class="iconfont" :class="menu.icon"></i>
                <span class="menu-title">{{ menu.title }}</span>
              </router-link>
            </template>
          </div>
        </template>
        <template v-if="hasManageMenus">
          <a class="menu-item sub-menu-item" @click="handleSubmenuShowChange">
            <i class="iconfont icon-quanxianshezhi"></i>
            <span class="menu-title">系统管理</span>
            <div class="arrow-icon">
              <i class="iconfont icon-xia" v-if="subMenuShow"></i>
              <i class="iconfont icon-shang" v-else></i>
            </div>
          </a>
          <div class="submenu-box" v-show="subMenuShow">
            <template v-for="menu in DefManageMenuList" :key="menu.menuCode">
              <router-link :to="menu.path" class="menu-item" :class="currentRoutePath === menu.path ? 'active' : ''" v-if="localRoleMenuCacheObj[menu.menuCode]">
                <div class="mask-active"></div>
                <i class="iconfont" :class="menu.icon"></i>
                <span class="menu-title">{{ menu.title }}</span>
              </router-link>
            </template>
          </div>
        </template>
      </div>
    </a-layout-sider>
    <a-layout-content class="dashboard-content">
      <div class="header-bar mb-12">
        <div class="user-info">
          <div class="avatar"></div>
          <a-dropdown>
            <a class="ant-dropdown-link" @click.prevent>
              {{ localUser.nickName || localUser.userName }}
              <DownOutlined/>
            </a>
            <template #overlay>
              <a-menu @click="handleDropdownMenuClick">
                <a-menu-item key="updatePassword">
                  <a href="javascript:;">修改密码</a>
                </a-menu-item>
                <a-menu-item key="logout">
                  <a href="javascript:;">退出登录</a>
                </a-menu-item>
              </a-menu>
            </template>
          </a-dropdown>
        </div>
      </div>
      <router-view/>
    </a-layout-content>
  </a-layout>
  <a-modal :width="520" title="修改密码" v-model:visible="modalVisible" :confirmLoading="saveLoading"
           @ok="handleSavePassword">
    <a-form
        layout="vertical"
        :model="formState"
        :rules="rules"
        ref="pwdForm">
      <a-form-item
          label="新密码"
          name="password">
        <a-input v-model:value="formState.password" placeholder="8-20位，只能包含数字、字母、下划线及!@#$%&*" :maxlength="20"></a-input>
      </a-form-item>
      <a-form-item
          label="再次输入新密码"
          name="againPassword">
        <a-input v-model:value="formState.againPassword" placeholder="8-20位，只能包含数字、字母、下划线及!@#$%&*"
                 :maxlength="20"></a-input>
      </a-form-item>
      <a-form-item
          label="">
        <a-button type="default" @click="handleRandomPassword">随机密码</a-button>
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script lang="ts" setup>
import {nextTick, ref} from 'vue';
import {DownOutlined} from '@ant-design/icons-vue';
import {useRouter, onBeforeRouteUpdate} from "vue-router";
import common from '../common/common'
import {MenuItem, ResDto, RoleMenuItem} from "../types/common";
import {DefAuthList, DefMenuList, DefManageMenuList, DefFinanceMenuList} from "../common/constants";
import {uuid} from "../common/utils";
import userApi from '../api/users'
import {message} from "ant-design-vue";

const formState = ref({
  password: '',
  againPassword: '',
})
const pwdForm = ref()
const rules = {
  password: [
    {required: true, trigger: 'blur', message: '请输入新密码'},
    {pattern: /^[a-zA-Z0-9_!@#$%&*]{8,20}$/gi, trigger: 'blur', message: '8-20位，只能包含数字、字母、下划线及!@#$%&*'},
  ],
  againPassword: [
    {required: true, trigger: 'blur', message: '请再次输入新密码'},
  ],
}
const modalVisible = ref<boolean>(false)
const saveLoading = ref<boolean>(false)
const localUser = ref(common.getLocalUser() || {})
const localRoleMenuList = common.getLocalRoleAuth() || []
const localRoleMenuCacheObj = ref({})
localRoleMenuList.forEach((roleMenu: RoleMenuItem) => {
  localRoleMenuCacheObj.value[roleMenu.menuCode] = roleMenu
})
const hasManageMenus = ref(false) // 是否有系统管理下的菜单权限
const hasFinanceMenus = ref(false) // 是否有系统管理下的菜单权限
DefManageMenuList.forEach((menu: MenuItem) => {
  if (localRoleMenuCacheObj.value[menu.menuCode]) {
    hasManageMenus.value = true
  }
})
DefFinanceMenuList.forEach((menu: MenuItem) => {
  if (localRoleMenuCacheObj.value[menu.menuCode]) {
    hasFinanceMenus.value = true
  }
})
// const menuList = ref([])
// DefAuthList.forEach((authMenu: MenuItem) => {
//   if (localRoleMenuCacheObj.value[authMenu.menuCode]) {
//     if (authMenu.type === 'menu') {
//       menuList.value.push({
//         path: authMenu.path,
//         title: authMenu.title,
//         icon: authMenu.icon,
//       })
//     }
//   }
//   if (authMenu.type === 'menu') {
//     menuList.value.push({
//       path: authMenu.path,
//       title: authMenu.title,
//       icon: authMenu.icon,
//     })
//   }
// })
const router = useRouter();
const currentRoutePath = ref(router.currentRoute.value.path)
onBeforeRouteUpdate((to, from, next) => {
  currentRoutePath.value = to.path;
  next()
});
const logout = () => {
  common.removeLocalUser()
  common.removeLocalToken()
  common.removeLocalRoleAuth()
  router.replace('/login')
}
const handleRandomPassword = () => {
  const str = uuid(12, 0, '0123456789_!@#$%&*ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz')
  formState.value.password = str
  formState.value.againPassword = str
}
const handleSavePassword = async () => {
  try {
    await pwdForm.value.validateFields()
    if (formState.value.password !== formState.value.againPassword) {
      message.error('两次输入的密码不一致')
      return
    }
    try {
      const res = await userApi.updatePwd(localUser.value.userName, formState.value.password)
      if (res.success) {
        message.success('密码修改成功')
        logout()
      } else {
        let msg = '操作失败'
        if (res.errors && res.errors[0] && res.errors[0].message) {
          msg = res.errors[0].message
        }
        message.error(msg)
      }
    } catch(e){
      if (e.errors && e.errors[0] && e.errors[0].message) {
        message.error(e.errors[0].message)
      }
    }
  } catch(e) {

  }
}
const handleDropdownMenuClick = (e: any) => {
  switch (e.key) {
    case 'logout':
      logout()
      break;
    case 'updatePassword':
      formState.value.password = ''
      formState.value.againPassword = ''
      modalVisible.value = true
      nextTick(() => {
        pwdForm.value.clearValidate()
      })
      break;
  }
}
const subMenuShow = ref(true)
const handleSubmenuShowChange = () => {
  subMenuShow.value = !subMenuShow.value
}

const subMenuShow2 = ref(true)
const handleSubmenuShowChange2 = () => {
  subMenuShow2.value = !subMenuShow2.value
}


</script>

<style scoped lang="less">
@import '/@/assets/styles/var.less';

.dashboard-page {
  position: relative;
  width: 100%;
  height: 100%;
  background: #ffffff;
  padding: 15px;
}

.dashboard-menu-sider {
  font-size: 14px;
  background: transparent;
  position: relative;
  padding: 0 30px 0 15px;

  .menu-list {
    position: relative;
    height: calc(100vh - 118px);
  }

  .menu-item {
    position: relative;
    width: 100%;
    height: 45px;
    line-height: 45px;
    padding-left: 20px;
    border-radius: 5px;
    color: @textColor;
    cursor: pointer;
    display: block;

    & + .menu-item {
      margin-top: 5px;
    }
    .arrow-icon{
      position: absolute;
      right: 20px;
      top:0;
    }
    .menu-title {
      position: relative;
      margin-left: 10px;
      font-size: 16px;
    }

    .iconfont {
      font-size: 18px;
    }

    &.active, &:hover {
      color: @primaryColor;
      background: @activeMaskBg;
      font-weight: bold;
    }
  }
  .sub-menu-item{
    &.active, &:hover {
      color: @primaryColor;
      background: transparent;
      font-weight: bold;
    }
  }
  .submenu-box{
    .menu-item{
      padding-left: 40px;
    }
  }
}

.dashboard-content {
  position: relative;
  flex: 1;
  background: @contentBgColor;
  padding: 10px 20px 20px;
  border-radius: 15px;

  .header-bar {
    position: relative;
    display: flex;
    justify-content: flex-end;

    .user-info {
      position: relative;
      display: flex;
      align-items: center;

      .avatar {
        position: relative;
        width: 34px;
        height: 34px;
        background-image: url("../assets/img/avatar.png");
        background-size: 100% 100%;
        background-repeat: no-repeat;
        margin-right: 12px;
      }
    }
  }
}

.logo-info {
  display: flex;
  align-items: center;
  position: relative;
  margin-bottom: 50px;

  .logo-box {
    width: 36px;
    height: 36px;
    background-image: url("../assets/img/logo_icon.png");
    background-size: 100% 100%;
    background-repeat: no-repeat;
    line-height: 36px;
    border-radius: 5px;
    //background: @primaryColor;
    text-align: center;

    .iconfont {
      color: #ffffff;
      font-size: 20px;
    }
  }

  .title {
    font-size: 20px;
    font-weight: bold;
    margin-left: 10px;
  }
}


</style>
